package com.baiyang.app.tool.net;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public abstract class SendMsgUtil {
    public static String cookie;
    public SendMsgUtil(){

    }
    public void sendPost(String url,Object object){
        Log.i("send", JSONObject.toJSONString(object));
        OkHttpClient okHttpClient = createClient();
        Request request = createPostRequest(url,object);
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.请求加入调度，重写回调方法
        call.enqueue(new Callback() {
            //请求失败执行的方法
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("error-->",e.getMessage());
                try {
                    cookie = null;
                    dealFailure(call,e);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            //请求成功执行的方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(cookie == null){
                    Headers headers = response.headers();
                    List<String> cookies = headers.values("Set-Cookie");
                    if(cookies.size() != 0){
                        cookie = cookies.get(0);
                    }
                }
                deal(call,response);
            }
        });
    }

    public void sendGet(String url){
        OkHttpClient okHttpClient = createClient();
        Request request = createGetRequest(url);
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.请求加入调度，重写回调方法
        call.enqueue(new Callback() {
            //请求失败执行的方法
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("error-->",e.getMessage());
                try {
                    cookie = null;
                    dealFailure(call,e);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            //请求成功执行的方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(cookie == null){
                    Headers headers = response.headers();
                    List<String> cookies = headers.values("Set-Cookie");
                    if(cookies.size() != 0){
                        cookie = cookies.get(0);
                    }
                }
                deal(call,response);
            }
        });
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    /** 传输文件 **/
    public void sendFile(String url,File file) throws Exception {
        Log.i("send",file.getName());
        //1.创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder().readTimeout(60, TimeUnit.SECONDS)
                .build();
        //2.创建RequestBody
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

        //3.构建MultipartBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        Request request = null;
        //4.构建请求
        if(cookie != null && !cookie.equals("")){
            request = new Request.Builder()
                    .url(url)
                    .addHeader("Cookie",cookie)
                    .post(requestBody)
                    .build();
        }else{
            throw new Exception("缺失cookie");
        }
        //5.发送请求
        Call call  = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("error-->",e.getMessage());
                try {
                    cookie = null;
                    dealFailure(call,e);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                deal(call,response);
            }
        });
    }

    public Response uploadFileAsyn(String url,File file) throws IOException {
        Log.i("send",file.getName());
        //1.创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder().connectTimeout(10, TimeUnit.SECONDS).
                        readTimeout(120, TimeUnit.SECONDS).build();
        //2.创建RequestBody
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

        //3.构建MultipartBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        Request request = null;
        //4.构建请求
        if(cookie != null && !cookie.equals("")){
            request = new Request.Builder()
                    .url(url)
                    .addHeader("Cookie",cookie)
                    .post(requestBody)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
        }


        //5.发送请求
        Call call  = okHttpClient.newCall(request);
        Response response = call.execute();
        return response;
    }

    public abstract void deal(Call call, Response response) throws IOException;
    public abstract void dealFailure(Call call, IOException e)throws IOException;

    private OkHttpClient createClient(){
        //1.创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        return okHttpClient;
    }

    /**
     * 创建post请求
     * @param url
     * @param object
     * @return
     */
    private Request createPostRequest(String url,Object object){
        //RequestBody中的MediaType指定为纯文本，编码方式是utf-8
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),
                JSONObject.toJSONString(object));
        //2.创建Request对象，设置一个url地址（百度地址）,设置请求方式。
        Request request = null;
        if(cookie != null && !cookie.equals("")){
            //需要设置cookie   用于spring security身份验证
            request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Cookie",cookie)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
        }
        return request;
    }

    /**
     * 创建get请求请求信息
     * @param url
     * @return
     */
    private Request createGetRequest(String url){
        //创建Request对象，设置一个url地址（百度地址）,设置请求方式。
        Request request = null;
        if(cookie != null && !cookie.equals("")){
            //需要设置cookie   用于spring security身份验证
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Cookie",cookie)
                    .build();
        }else{
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        }
        return request;
    }


}
